import { Catch } from '@midwayjs/core';
import { MidwayValidationError } from '@midwayjs/validate';
import {
  ForbiddenError,
  UnauthorizedError,
} from '@midwayjs/core/dist/error/http';

@Catch(MidwayValidationError)
export class ValidateErrorFilter {
  async catch(err: MidwayValidationError) {
    return {
      code: 1,
      msg: '校验参数错误,' + err.message,
    };
  }
}

@Catch(UnauthorizedError)
export class UnauthorizedErrorFilter {
  async catch(err: UnauthorizedError) {
    return {
      code: 401,
      msg: err.message,
    };
  }
}

@Catch(ForbiddenError)
export class ForbiddenErrorFilter {
  async catch(err: ForbiddenError) {
    return {
      code: 403,
      msg: err.message,
    };
  }
}

@Catch()
export class DefaultErrorFilter {
  async catch(err: Error) {
    if (err.name === 'PayloadTooLargeError') {
      return {
        code: 1,
        msg: '上传文件大小超过限制',
      };
    }
    return {
        code: 1,
        msg: err.message
      };
  }
}
